import React, { useState, forwardRef, useImperativeHandle } from 'react';
import { Modal, Input, Radio, message } from 'antd';
import { useradd, edituserFn } from '@/api/user';
// 模态框组件
const Mymodal = forwardRef((props, ref) => {
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [currentUser, setCurrentUser] = useState({ gender: '1' });
	// 定义模态框标题
	const [title, setTitle] = useState('')

	const showModal = () => {
		// console.log('111');
		setIsModalOpen(true);
	};
	// 确认按钮
	const handleOk = () => {
		setIsModalOpen(false);
		if (title === '添加') {
			useradd(currentUser).then(res => {
				// console.log(res)
				if (res.data.errNo === 0) {
					message.success('添加成功', 1, () => {
						props.getuserlistHandler({ page: props.page })
						setCurrentUser({ gender: '1' })
					})
				} else {
					message.error(res.data.errText, 1, () => {
						setCurrentUser({ gender: '1' })
					})
				}
				
			})
		} else if (title === '编辑') {
			edituserFn(currentUser).then(res => {
				// console.log('编辑接口', res)
				if (res.data.errNo === 0) {
					message.success('编辑成功!', 1, () => {
						props.getuserlistHandler({ page: props.page })
						setCurrentUser({ gender: '1' })
					})
				} else {
					message.error(res.data.errText, 1)
					setCurrentUser({ gender: '1' })
				}
			})
		}
	};
	
	const handleCancel = () => {
		setIsModalOpen(false);
		setCurrentUser({ gender: '1' })
	};

	// 使用 useImperativeHandle  抛出当前函数组件上的数据和方法
	useImperativeHandle(ref, () => {
		return {
			isModalOpen,
			showModal,
			setTitle,
			setCurrentUser
		}
	})
	//
	const onChange = (key, e) => {
		// console.log('radio checked', e.target.value);
		currentUser[key] = e.target.value
		setCurrentUser({ ...currentUser });
		// console.log(currentUser)
	};

	return (

		<Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
			<p> <Input placeholder="用户名" value={currentUser.username} onChange={(e) => onChange('username', e)} /></p>
			<p> <Input placeholder="密码" value={currentUser.password} onChange={(e) => onChange('password', e)} /></p>
			<p> <Input placeholder="手机号" value={currentUser.mobile} onChange={(e) => onChange('mobile', e)} /></p>
			<div>
				<Radio.Group onChange={(e) => onChange('gender', e)} value={currentUser.gender}>
					<Radio value={'1'}>男</Radio>
					<Radio value={'2'}>女</Radio>
					<Radio value={'3'}>保密</Radio>
				</Radio.Group>
			</div>
			<p> <Input placeholder="邮箱" value={currentUser.email} onChange={(e) => onChange('email', e)} /></p>
		</Modal>
	);
})

export default Mymodal;
